#!/bin/bash

# SpringBoot项目启动环境检查脚本
# 版本: 2.0.0
# 设计: SpringBoot启动问题诊断与解决方案

set -e  # 遇到错误时停止执行

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 计数器
error_count=0
warning_count=0
check_count=8

# 创建日志文件
log_dir="logs"
log_file="${log_dir}/environment-check-$(date +%Y%m%d-%H%M%S).log"
mkdir -p "$log_dir"

echo "========================================" | tee "$log_file"
echo "      招聘系统后端环境检查脚本        " | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "版本: 2.0.0" | tee -a "$log_file"
echo "设计: SpringBoot启动问题诊断与解决方案" | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "" | tee -a "$log_file"

echo "[$(date)] 开始环境检查" >> "$log_file"

# 检查Java版本
echo "[1/$check_count] 检查Java环境..." | tee -a "$log_file"
if command -v java &> /dev/null; then
    echo -e "${GREEN}✅ Java环境正常${NC}" | tee -a "$log_file"
    java_version=$(java -version 2>&1 | head -n 1)
    echo "    $java_version" | tee -a "$log_file"
    
    # 检查Java版本是否符合要求(17+)
    java_major=$(java -version 2>&1 | sed -n ';s/.* version "\([0-9]*\)\..*$/\1/p;')
    if [ "$java_major" -lt 17 ]; then
        echo -e "${YELLOW}⚠️  警告: Java版本过低，建议使用Java 17或更高版本${NC}" | tee -a "$log_file"
        echo "[WARN] Java版本过低: $java_version" >> "$log_file"
        ((warning_count++))
    fi
else
    echo -e "${RED}❌ Java未正确安装或未添加到PATH${NC}" | tee -a "$log_file"
    echo "[ERROR] Java未正确安装或未添加到PATH" >> "$log_file"
    ((error_count++))
fi

# 检查Maven版本
echo "" | tee -a "$log_file"
echo "[2/$check_count] 检查Maven环境..." | tee -a "$log_file"
if command -v mvn &> /dev/null; then
    echo -e "${GREEN}✅ Maven环境正常${NC}" | tee -a "$log_file"
    maven_version=$(mvn -version 2>&1 | head -n 1)
    echo "    $maven_version" | tee -a "$log_file"
else
    echo -e "${RED}❌ Maven未正确安装或未添加到PATH${NC}" | tee -a "$log_file"
    echo "[ERROR] Maven未正确安装或未添加到PATH" >> "$log_file"
    ((error_count++))
fi

# 检查MySQL服务
echo "" | tee -a "$log_file"
echo "[3/$check_count] 检查MySQL服务..." | tee -a "$log_file"
if netstat -an 2>/dev/null | grep -q ":3306 " || ss -an 2>/dev/null | grep -q ":3306 "; then
    echo -e "${GREEN}✅ MySQL服务正常运行（端口3306）${NC}" | tee -a "$log_file"
    
    # 尝试测试数据库连接
    echo "    正在测试数据库连接..."
    if command -v mysql &> /dev/null; then
        if mysql -u root -p123456 -e "SELECT 1;" &> /dev/null; then
            echo -e "    ${GREEN}✅ 数据库连接测试成功${NC}" | tee -a "$log_file"
        else
            echo -e "    ${YELLOW}⚠️  数据库连接测试失败，请检查用户名密码${NC}" | tee -a "$log_file"
            echo "[WARN] 数据库连接测试失败" >> "$log_file"
            ((warning_count++))
        fi
    else
        echo -e "    ${YELLOW}⚠️  mysql客户端未安装，无法测试连接${NC}" | tee -a "$log_file"
        echo "[WARN] mysql客户端未安装" >> "$log_file"
        ((warning_count++))
    fi
else
    echo -e "${RED}❌ MySQL服务未启动，端口3306未监听${NC}" | tee -a "$log_file"
    echo "    请启动MySQL服务: sudo systemctl start mysql" | tee -a "$log_file"
    echo "    或检查MySQL配置文件中的端口设置" | tee -a "$log_file"
    echo "[ERROR] MySQL服务未启动，端口3306未监听" >> "$log_file"
    ((error_count++))
fi

# 检查Redis服务（可选）
echo "" | tee -a "$log_file"
echo "[4/$check_count] 检查Redis服务..." | tee -a "$log_file"
if netstat -an 2>/dev/null | grep -q ":6379 " || ss -an 2>/dev/null | grep -q ":6379 "; then
    echo -e "${GREEN}✅ Redis服务正常运行（端口6379）${NC}" | tee -a "$log_file"
    
    # 测试Redis连接
    echo "    正在测试Redis连接..."
    if command -v redis-cli &> /dev/null; then
        if redis-cli ping &> /dev/null; then
            echo -e "    ${GREEN}✅ Redis连接测试成功${NC}" | tee -a "$log_file"
        else
            echo -e "    ${YELLOW}⚠️  Redis连接测试失败${NC}" | tee -a "$log_file"
            echo "[WARN] Redis连接测试失败" >> "$log_file"
            ((warning_count++))
        fi
    else
        echo -e "    ${YELLOW}⚠️  redis-cli未安装，无法测试连接${NC}" | tee -a "$log_file"
        echo "[WARN] redis-cli未安装" >> "$log_file"
        ((warning_count++))
    fi
else
    echo -e "${YELLOW}⚠️  Redis服务未启动，系统将以无缓存模式运行${NC}" | tee -a "$log_file"
    echo "    建议启动Redis服务以获得更好的性能" | tee -a "$log_file"
    echo "    Linux: sudo systemctl start redis" | tee -a "$log_file"
    echo "    或使用Docker: docker run -d -p 6379:6379 redis" | tee -a "$log_file"
    echo "[WARN] Redis服务未启动，系统将以无缓存模式运行" >> "$log_file"
    ((warning_count++))
fi

# 检查端口占用
echo "" | tee -a "$log_file"
echo "[5/$check_count] 检查应用端口..." | tee -a "$log_file"
if netstat -an 2>/dev/null | grep -q ":8080 " || ss -an 2>/dev/null | grep -q ":8080 "; then
    echo -e "${RED}❌ 端口8080已被占用${NC}" | tee -a "$log_file"
    echo "    请停止占用端口8080的进程" | tee -a "$log_file"
    echo "    占用端口的进程信息：" | tee -a "$log_file"
    if command -v lsof &> /dev/null; then
        lsof -i :8080 | tee -a "$log_file"
    else
        netstat -tulpn | grep :8080 | tee -a "$log_file"
    fi
    echo "[ERROR] 端口8080已被占用" >> "$log_file"
    ((error_count++))
else
    echo -e "${GREEN}✅ 端口8080可用${NC}" | tee -a "$log_file"
fi

# 检查项目依赖
echo "" | tee -a "$log_file"
echo "[6/$check_count] 检查项目依赖..." | tee -a "$log_file"
if [ -f "backend/pom.xml" ]; then
    echo -e "${GREEN}✅ 找到Maven项目配置文件${NC}" | tee -a "$log_file"
    
    cd backend
    echo "    正在验证Maven依赖..."
    if mvn dependency:resolve -q &> /dev/null; then
        echo -e "    ${GREEN}✅ Maven依赖验证成功${NC}" | tee -a "../$log_file"
    else
        echo -e "    ${YELLOW}⚠️  Maven依赖解析可能存在问题${NC}" | tee -a "../$log_file"
        echo "    建议运行: mvn clean install" | tee -a "../$log_file"
        echo "[WARN] Maven依赖解析可能存在问题" >> "../$log_file"
        ((warning_count++))
    fi
    cd ..
else
    echo -e "${RED}❌ 未找到Maven项目配置文件 (backend/pom.xml)${NC}" | tee -a "$log_file"
    echo "[ERROR] 未找到Maven项目配置文件" >> "$log_file"
    ((error_count++))
fi

# 检查配置文件
echo "" | tee -a "$log_file"
echo "[7/$check_count] 检查配置文件..." | tee -a "$log_file"
if [ -f "backend/src/main/resources/application.yml" ]; then
    echo -e "${GREEN}✅ 找到主配置文件${NC}" | tee -a "$log_file"
else
    echo -e "${RED}❌ 未找到主配置文件 application.yml${NC}" | tee -a "$log_file"
    echo "[ERROR] 未找到主配置文件" >> "$log_file"
    ((error_count++))
fi

if [ -f "backend/src/main/resources/application-dev.yml" ]; then
    echo -e "${GREEN}✅ 找到开发环境配置文件${NC}" | tee -a "$log_file"
else
    echo -e "${YELLOW}⚠️  未找到开发环境配置文件 application-dev.yml${NC}" | tee -a "$log_file"
    echo "[WARN] 未找到开发环境配置文件" >> "$log_file"
    ((warning_count++))
fi

# 检查磁盘空间
echo "" | tee -a "$log_file"
echo "[8/$check_count] 检查磁盘空间..." | tee -a "$log_file"
free_space=$(df . | awk 'NR==2 {print $4}')
if [ "$free_space" -lt 1048576 ]; then  # 少于1GB (1024*1024 KB)
    echo -e "${RED}❌ 磁盘可用空间不足 (少于1GB)${NC}" | tee -a "$log_file"
    echo "[ERROR] 磁盘可用空间不足" >> "$log_file"
    ((error_count++))
else
    echo -e "${GREEN}✅ 磁盘空间充足${NC}" | tee -a "$log_file"
fi